// 包含 wx.request需要的参数和返回值，还有请求过程中的Loading提示，Toast提示
const setInfo = require('../const').SET_INFO;
const baseURL = setInfo.api_root;

const Request = (options) =>{
  var tokenKey = wx.getStorageSync('token'); //全局token
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '请求中',
    })
    wx.hideLoading()
    options.data.token = tokenKey;
    options.data.room_id = setInfo.ROOM_ID;
    wx.request({
      url: baseURL + options.url || '',
      data: options.data || {},
      method: options.method === 'POST' ? 'POST' : 'GET',
      header:{'content-type': "application/x-www-form-urlencoded",'Authorization':tokenKey},
      responseType:options.responseType || "",
      timeout:1000,
      success (res) {
        wx.hideLoading();
        if(res.statusCode == 200){
            // console.log(res,"res1111");
            if(res.data.code == -10){
                wx.setStorageSync('token',"")
                wx.setStorageSync('userInfo',"")
                var pages = getCurrentPages();
                if(setInfo.tapbarList.indexOf(pages[pages.length-1].route) > -1){
                    wx.reLaunch({
                        url: '/' + pages[pages.length-1].route,
                    });
                }else{
                    wx.navigateTo({
                        url: '/' + pages[pages.length-1].route,
                    });
                }
              
            }
            else if(res.data.code < 0){
                wx.showToast({
                    icon:'error',
                    title: res.data.message,
                })
            }
            resolve(res)
        }else{
            console.log(res,"res");
            wx.showToast({
              title: res.data.message,
            })
        };
      },
      fail (res) {
        // wx.showToast({
        //     title: res.message,
        // })
        // reject(res);
      }
    })
  })
};

module.exports = {
  Request,
};